﻿using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WeChatDemo.Models;

namespace WeChatDemo;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private ObservableCollection<ChatMessage> messages;
    private string currentContact;

    public MainWindow()
    {
        InitializeComponent();
        InitializeChatList();
        InitializeMessageList();
    }

    #region Window Control
    private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ClickCount == 2)
        {
            MaximizeButton_Click(null, null);
        }
        else
        {
            DragMove();
        }
    }

    private void MinimizeButton_Click(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState.Minimized;
    }

    private void MaximizeButton_Click(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
    }

    private void CloseButton_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
    #endregion

    #region Emoji Handling
    private void EmojiButton_Click(object sender, RoutedEventArgs e)
    {
        EmojiPopup.IsOpen = !EmojiPopup.IsOpen;
    }

    private void EmojiItem_Click(object sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            string emoji = button.Content.ToString();
            int caretIndex = MessageInput.CaretIndex;
            MessageInput.Text = MessageInput.Text.Insert(caretIndex, emoji);
            MessageInput.CaretIndex = caretIndex + emoji.Length;
            MessageInput.Focus();
            EmojiPopup.IsOpen = false;
        }
    }
    #endregion

    private void InitializeMessageList()
    {
        messages = new ObservableCollection<ChatMessage>();
        MessageList.ItemsSource = messages;
    }

    private void InitializeChatList()
    {
        // 添加示例聊天项
        for (int i = 1; i <= 10; i++)
        {
            var item = CreateChatItem($"联系人 {i}", $"最新消息 {i}", "12:00");
            item.Tag = $"联系人 {i}";
            item.Selected += ChatItem_Selected;
            ChatList.Items.Add(item);
        }
    }

    private void ChatItem_Selected(object sender, RoutedEventArgs e)
    {
        var item = sender as ListViewItem;
        if (item != null)
        {
            currentContact = item.Tag as string;
            messages.Clear();
            
            // 添加一些示例消息
            messages.Add(new ChatMessage($"你好，我是{currentContact}", false));
            messages.Add(new ChatMessage("你好！很高兴认识你", true));
            messages.Add(new ChatMessage("今天天气真不错", false));

            // 更新标题
            Title = currentContact;
        }
    }

    private ListViewItem CreateChatItem(string name, string message, string time)
    {
        var grid = new Grid();
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(50) });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });

        // 头像
        var avatar = new Border
        {
            Width = 40,
            Height = 40,
            CornerRadius = new CornerRadius(4),
            Background = new System.Windows.Media.SolidColorBrush(
                (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#CCCCCC")),
            Margin = new Thickness(5)
        };

        var avatarIcon = new TextBlock
        {
            Text = "👤",
            FontSize = 24,
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
            Foreground = System.Windows.Media.Brushes.White
        };

        avatar.Child = avatarIcon;
        Grid.SetColumn(avatar, 0);

        // 名称和消息
        var textStack = new StackPanel { Margin = new Thickness(5, 5, 0, 5) };
        textStack.Children.Add(new TextBlock
        {
            Text = name,
            FontSize = 14,
            Margin = new Thickness(0, 0, 0, 4)
        });
        textStack.Children.Add(new TextBlock
        {
            Text = message,
            Foreground = System.Windows.Media.Brushes.Gray
        });
        Grid.SetColumn(textStack, 1);

        // 时间
        var timeText = new TextBlock
        {
            Text = time,
            Foreground = System.Windows.Media.Brushes.Gray,
            Margin = new Thickness(5),
            VerticalAlignment = VerticalAlignment.Top
        };
        Grid.SetColumn(timeText, 2);

        grid.Children.Add(avatar);
        grid.Children.Add(textStack);
        grid.Children.Add(timeText);

        return new ListViewItem
        {
            Content = grid,
            Height = 65,
            Padding = new Thickness(0),
            BorderThickness = new Thickness(0)
        };
    }

    private void SendMessage()
    {
        var message = MessageInput.Text.Trim();
        if (!string.IsNullOrEmpty(message))
        {
            messages.Add(new ChatMessage(message, true));
            MessageInput.Clear();

            // 模拟回复
            var random = new Random();
            var replies = new[]
            {
                "好的，我知道了",
                "嗯嗯",
                "确实如此",
                "有道理",
                "让我想想...",
                "有意思"
            };

            var reply = replies[random.Next(replies.Length)];
            Task.Delay(1000).ContinueWith(_ =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    messages.Add(new ChatMessage(reply, false));
                    ScrollToBottom();
                });
            });

            ScrollToBottom();
        }
    }

    private void ScrollToBottom()
    {
        MessageScrollViewer.ScrollToBottom();
    }

    private void SendButton_Click(object sender, RoutedEventArgs e)
    {
        SendMessage();
    }

    private void MessageInput_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter && !e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Shift))
        {
            e.Handled = true;
            SendMessage();
        }
    }

    private void ChatButton_Click(object sender, RoutedEventArgs e)
    {
        // 处理聊天按钮点击
    }

    private void ContactsButton_Click(object sender, RoutedEventArgs e)
    {
        // 处理联系人按钮点击
    }

    private void CollectionButton_Click(object sender, RoutedEventArgs e)
    {
        // 处理收藏按钮点击
    }
}